package com.shop.servlet;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.Base64;

@WebServlet("/refreshCaptcha")
public class RefreshCaptchaServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[4];
        random.nextBytes(bytes);
        String captcha = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes).substring(0, 4).toUpperCase();

        // 将验证码存入request而非session
        request.setAttribute("captcha", captcha);
        response.setContentType("text/plain");
        response.getWriter().write(captcha);
    }
}
